/*****************************************************************
 *Yuga Technology
 *@author Oplink OMS
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webems.modules.topo.web;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.common.utils.AlarmUtils;
import com.oplink.webems.common.utils.UserUtils;
import com.oplink.webems.modules.cfg.entity.CfgNe;
import com.oplink.webems.modules.cfg.entity.CfgSite;
import com.oplink.webems.modules.cfg.services.CfgNeService;
import com.oplink.webems.modules.cfg.services.CfgSiteService;
import com.oplink.webems.modules.sys.entity.User;
import com.oplink.webems.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webems.modules.sys.web.BaseController;
import com.oplink.webems.modules.topo.entity.Topo;
import com.oplink.webems.modules.topo.service.TopoService;

@Controller
@RequestMapping(value = "topo")
public class TopoController extends BaseController {
	
	@Autowired
	private TopoService topoService;
	@Autowired
	private CfgSiteService cfgSiteService;
	@Autowired
	private CfgNeService neService;
	
	@RequestMapping(value="index")
	public String showTopo(HttpServletRequest req, HttpServletResponse res){
		try {
			Topo t = topoService.findByTopoId(0L);
			
			req.setAttribute("content", t==null?"":t.getContent());
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return "modules/topo/index";
	}
	
	@RequestMapping(value="subTopo/{topoId}")
	public String showSubTopo(@PathVariable("topoId") String topoId, RedirectAttributes redirectAttributes, Model model){
		try {
			Topo t = topoService.findByTopoId(Long.parseLong(topoId));
			model.addAttribute("topoId", topoId);
			model.addAttribute("content", t==null?"":t.getContent());
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return "modules/topo/subTopo";
	}
	
	@RequestMapping(value="topoLink/{fromName}/{toName}")
	public String showTopoLink(@PathVariable("fromName") String fromName,@PathVariable("toName") String toName, RedirectAttributes redirectAttributes, Model model){
		model.addAttribute("fromName",fromName);
		model.addAttribute("toName",toName);
		return "modules/topo/topoLink";
	}
	
	@RequestMapping(value="getNodesByTopoId")
	public String getNodesByTopoId(HttpServletRequest req, HttpServletResponse res){
		try {
			long topoId = Long.parseLong(req.getParameter("id"));
			if(topoId==0){
				List<CfgSite> list = cfgSiteService.getAllSite();
				
				JSONArray listJson = (JSONArray) JSONObject.toJSON(list);
				//填入所有告警等级与数字
				for(int i=0; i<listJson.size(); i++){
					JSONObject aJson = (JSONObject) listJson.get(i);
					/*int[] levelAndCount = AlarmUtils.getAlarmHLevelAndCount(list.get(i));*/
					
					TreeMap<Integer, Integer>  _treeMap = AlarmUtils.getSiteAlarmCount(list.get(i));
					
					aJson.put("alarmLevelArr", _treeMap.keySet().toArray());
					aJson.put("alarmCountArr", _treeMap.values().toArray());
				}
				res.getWriter().write(listJson.toJSONString());
			}else{
				List<CfgNe> list = neService.findAllNeBySite(topoId);
				
				JSONArray listJson = (JSONArray) JSONObject.toJSON(list);
				
				//填入所有告警等级与数字
				for(int i=0; i<listJson.size(); i++){
					JSONObject aJson = (JSONObject) listJson.get(i);
					/*int[] levelAndCount = AlarmUtils.getAlarmHLevelAndCount(list.get(i));*/
					TreeMap<Integer, Integer>  _treeMap = AlarmUtils.getCfgNeAlarmCount(list.get(i));
					
					
					aJson.put("alarmLevelArr", _treeMap.keySet().toArray());
					aJson.put("alarmCountArr", _treeMap.values().toArray());
				}
				res.getWriter().write(listJson.toJSONString());
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value="save")
	public void save(HttpServletRequest req, HttpServletResponse res){
		JSONObject o = new JSONObject();
		
		PrintWriter write = null;
		try{
			write = res.getWriter();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			Topo t = new Topo();
			t.setTopoid(Long.parseLong(req.getParameter("topoId")));
			t.setContent(req.getParameter("content"));
			t.setUser(new User(UserUtils.getCurrentUserId()));
			
			boolean ret;
			if(topoService.findByTopoId(t.getTopoid())!=null){
				ret = topoService.updateTopo(t);
			}else{
				ret = topoService.save(t);
			}		 
			
			o.put("result", ret);
		}catch(Exception e){
			e.printStackTrace();
			o.put("result", false);
		}finally{
			write.write(o.toJSONString());
		}
		
	}
	
	@RequiresPermissions("modules/topo:topoentity:view")
	@RequestMapping(value = {"list", ""}, method = {RequestMethod.GET, RequestMethod.POST})
	public String list(Topo topoentity, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long userId = getCurrentUserId();

		Page<Topo> pages = topoService.find(new Page<Topo>(request, response), topoentity);         
		//Page<Topoentity> pages = topoentityService.getUserTopoentity(userId, searchParams, pageNumber, pageSize, sortType);
		model.addAttribute("pages", pages);
		model.addAttribute("userId", userId);

		// 将搜索条件编码成字符串，用于排序，分页的URL
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "modules/topo/topoentityList";
	}

	@RequiresPermissions("modules/topo:topoentity:edit")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Topo updateForm(@PathVariable("id") Long id) {
		Topo topoentity = topoService.getTopoentity(id);
		topoentity.setUser(null);
		return topoentity;
	}
	
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("topoentity") Topo topoentity, RedirectAttributes redirectAttributes) {
		try {
			User user = new User(getCurrentUserId());
			topoentity.setUser(user);
			topoService.saveTopoentity(topoentity);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}
	
	@RequiresPermissions("modules/topo:topoentity:view")
	@RequestMapping(value = "form")
	public String form(Topo topoentity, Model model) {
		model.addAttribute("topoentity", topoentity);
		return "modules/topo/topoentityForm";
	}

	@RequiresPermissions("modules/topo:topoentity:edit")
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("userId", getCurrentUserId());
		model.addAttribute("action", "create");
		return "modules/topo/topoentity/create";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(Topo topoentity, RedirectAttributes redirectAttributes, Model model) {
		try {
			User user = new User(getCurrentUserId());
			topoentity.setUser(user);
			model.addAttribute("topoentity", topoentity);
			topoService.saveTopoentity(topoentity);
			redirectAttributes.addFlashAttribute("message", "创建任务成功");
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					topoService.deleteTopoentity(Long.valueOf(idItem));
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			return "0";
		}
	}
	
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
	
	@Autowired
	public void setTopoService(TopoService ts){
		this.topoService = ts;
	}
}
